// pages/music-palyer/index.js
const globalData = getApp().globalData

// evevtstore
import {
  audioContext,
  playerStore
} from "../../../store/index.js"

import debounce from "../../../utils/debounce"

const debounceNext = debounce(() => {
  playerStore.dispatch("changeNewMusicAction")
})

const debouncePrev = debounce(() => {
  playerStore.dispatch("changeNewMusicAction", false)
})

const playModeNames = ["order", "repeat", "random"]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    songInfo: {}, // 当前歌曲
    lyricInfos: [], // 歌曲歌词信息 
    duartionTime: 0, // 歌曲总时长

    currentTime: 0, // 歌曲当前的播放时间点
    currentIndex: 0, // 当前歌词在  lyricInfos 中的索引
    currentLyric: "", // 当前歌曲歌词

    playModeIndex: 0,
    playModeName: "order", // 当前播放模式

    isPlaying: false,
    playingName: "pause",


    currentPage: 0, // 当前处于 歌词 还是 歌曲
    swiperHeight: 0, // swiper高度
    scrollTopHeight: 0, // 歌词页面 的 应该向上滚动高度

    sliderValue: 0, // 当前滑块所处的位置 代表的值  总值是 0 - 100
    isSliderChanging: false, // 滑块 是否正在 滑动

    playAnimState: "paused"

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    // 设置swiper的高度 因为swiper的默认高度是 250px
    const screenHeight = globalData.screenHeight
    const statusBarHeight = globalData.statusBarHeight;
    const navigateBarHeight = globalData.navigateBarHeight;
    const swiperHeight = screenHeight - statusBarHeight - navigateBarHeight;
    this.setData({
      swiperHeight
    })

    const id = options.id;
    this.setData({
      id
    });

    // 监听 状态值得变化  并给data里面的数据重新赋值
    this.setupPlayerStoreListener()
  },


  // ============  事件处理  ===============
  // 1 轮播图 滑动触发事件
  handleCurrentChange(event) {
    const current = event.detail.current;
    this.setData({
      currentPage: current
    })
  },

  // 2 slider 进度条改变事件
  handleSliderChange(event) {
    // 1 获取点击后 slider的位置
    const value = event.detail.value;

    // 2 计算出 歌曲应该播放的时间点
    const currentTime = (value * this.data.duartionTime) / 100 // 单位ms

    // 3 在跳转歌曲进度之前 先暂停歌曲播放
    // audioContext.pause() // 由于在store里面 进行了 音乐的播放 和 暂停监听；回调函数里面的功能与这里冲突

    // 4 将歌曲跳转到 应该播放的时间点
    audioContext.seek(currentTime / 1000) // seek方法要求 单位为 s 

    // 5 更新 data 中的value值
    this.setData({
      sliderValue: value,
      isSliderChanging: false
    })

    playerStore.setState("isPlaying", true)
  },

  // 3 slider 滑块拖动事件
  handleSliderChanging(event) {
    const value = event.detail.value;
    const currentTime = (value * this.data.duartionTime) / 100 // 单位ms
    this.setData({
      isSliderChanging: true,
      currentTime,
    })
  },

  // 4 返回按钮点击事件
  handleBackClick() {
    wx.navigateBack()
  },

  // 5 播放模式
  handlePalyModeChange() {
    let playModeIndex = this.data.playModeIndex;
    playModeIndex++;
    if (playModeIndex === 3) playModeIndex = 0;
    playerStore.setState("playModeIndex", playModeIndex)
  },

  // 6 开始 或 暂停播放
  handleClickIsPlay() {
    playerStore.dispatch("changeMusicPlayStatusAction", !this.data.isPlaying)
  },

  // 7 播放上一首
  handlePrevClick() {
    debouncePrev()
  },
  // 8 播放下一首
  handleNextClick() {
    debounceNext()
  },

  // 9 展示歌曲列表的按钮 点击
  handleSongListClick() {
    playerStore.setState("isShowSongList", true)
  },

  // 10 歌曲列表展示时 遮罩层点击 隐藏列表
  handleBgCoverClick() {
    playerStore.setState("isShowSongList", false)
  },

  // 11 播放列表 播放
  handlePlayClick(event) {
    const index = event.currentTarget.dataset.index;
    const id = this.data.playListSongs[index].id
    playerStore.dispatch("palyMusicWithSongIdAction", {
      id,
      isRefresh: true
    })
    playerStore.setState("isShowSongList", false)
    playerStore.setState("playSongIndex", index)
  },

  // 12 播放列表删除
  handleDeleteClick(event) {
    const index = event.currentTarget.dataset.index;
    playerStore.dispatch("deleteSongFromPlaySongListAction", {
      index
    })
  },



  //  ===============   数据监听 ===============
  handleMusicPlayDataListenerOne({
    songInfo,
    duartionTime,
    lyricInfos
  }) {
    if (songInfo) this.setData({
      songInfo
    })
    if (duartionTime) this.setData({
      duartionTime
    })
    if (lyricInfos) this.setData({
      lyricInfos
    })
  },

  handleMusicPlayDataListenerTwo({
    currentTime,
    currentIndex,
    currentLyric
  }) {
    if (currentTime && !this.data.isSliderChanging) {
      const sliderValue = (100 * currentTime) / this.data.duartionTime
      this.setData({
        currentTime,
        sliderValue
      })
    }

    if (currentIndex) {
      this.setData({
        currentIndex,
        scrollTopHeight: currentIndex * 41
      })
    }

    if (currentLyric) {
      this.setData({
        currentLyric
      })
    }
  },

  handleMusicPlayDataListenerThree({
    playModeIndex,
    isPlaying
  }){
    if (playModeIndex !== undefined) {
      const playModeName = playModeNames[playModeIndex]
      this.setData({
        playModeIndex,
        playModeName
      })
    }

    if (isPlaying !== undefined) {
      const playingName = isPlaying ? "play" : "pause"
      this.setData({
        isPlaying,
        playingName,
        playAnimState: isPlaying ? "runing" : "paused"
      })
    }
  },

  handleMusicPlayDataListenerFour({
    playListSongs,
    playSongIndex,
    isShowSongList
  }){
    if (playListSongs !== undefined) this.setData({
      playListSongs
    })

    if (playSongIndex !== undefined) {
      this.setData({
        playSongIndex
      })
    }

    if (isShowSongList !== undefined) this.setData({
      isShowSongList
    })
  },


  //  =================  监听eventstore里面的数据变化 ==================
  setupPlayerStoreListener() {
    // 1  'songInfo','duartionTime','lyricInfos'
    playerStore.onStates(['songInfo', 'duartionTime', 'lyricInfos'], this.handleMusicPlayDataListenerOne)

    // 2  'currentTime','currentIndex','currentLyric'
    playerStore.onStates(['currentTime', 'currentIndex', 'currentLyric'], this.handleMusicPlayDataListenerTwo)

    // 3 playModeIndex isPlaying
    playerStore.onStates(['playModeIndex', 'isPlaying'], this.handleMusicPlayDataListenerThree)

    // 4 playListSongs playSongIndex isShowSongList
    playerStore.onStates(["playListSongs", "playSongIndex", 'isShowSongList'], this.handleMusicPlayDataListenerFour)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    playerStore.offStates(['songInfo', 'duartionTime', 'lyricInfos'], this.handleMusicPlayDataListenerOne);
    playerStore.offStates(['currentTime', 'currentIndex', 'currentLyric'], this.handleMusicPlayDataListenerTwo);
    playerStore.offStates(['playModeIndex', 'isPlaying'], this.handleMusicPlayDataListenerThree);
    playerStore.offStates(["playListSongs", "playSongIndex", 'isShowSongList'], this.handleMusicPlayDataListenerFour)
  },
})